<?php

/**
 * This is the model class for table "{{news}}".
 */
class News extends CActiveRecord
{
	private $_newsUrl;
	private $_oldTags;
	public $tagLinks;
	private $_userId = 0;
	/**
	 * The followings are the available columns in table '{{news}}':
	 * @var integer $news_id
	 * @var integer $link_id
	 * @var string $link_url
	 * @var string $url_hash
	 * @var string $url_host
	 * @var string $site_title
	 * @var string $news_desc
	 * @var integer $user_id
	 * @var string $user_name
	 * @var integer $digg_num
	 * @var integer $trash_num
	 * @var integer $comment_num
	 * @var string $post_time
	 * @var string $update_time
	 * @var integer $news_score
	 * @var string $news_thumb
	 */

	/**
	 * Returns the static model of the specified AR class.
	 * @return News the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{news}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('link_url, site_title', 'required'),
			array('link_url','ncValidateUrl'),
			array('news_desc', 'safe'),
			array('news_tag','normalizeTags'),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
		);
	}
	
	public function ncValidateUrl($attribute,$params){
		$pattern1='/^(http|https):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)/i';
		$pattern2='/^(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)/i';
		if(preg_match($pattern1,$this->link_url) || preg_match($pattern2,$this->link_url))
			return true;
		else $this->addError('link_url','输入的URL格式不对！');
	}
	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		if(!Yii::app()->user->isGuest){
			$this->_userId = Yii::app()->user->id;
		}
		return array(
			'comments' => array(self::HAS_MANY,'Comments','news_id'),
			'actions' => array(self::HAS_MANY,'Actions','news_id','condition'=>"actions.user_id=".$this->_userId),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'news_id' => 'News',
			'link_id' => 'Link',
			'link_url' => '地址',
			'url_hash' => 'Url Hash',
			'url_host' => 'Url Host',
			'site_title' => '标题',
			'news_tag' => '标签',
			'news_desc' => '描述',
			'user_id' => 'User',
			'user_name' => 'User Name',
			'digg_num' => 'Digg Num',
			'trash_num' => 'Trash Num',
			'comment_num' => 'Comment Num',
			'post_time' => 'Post Time',
			'update_time' => 'Update Time',
			'news_score' => 'News Score',
			'news_thumb' => '缩略图',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('news_id',$this->news_id);

		$criteria->compare('link_id',$this->link_id);

		$criteria->compare('link_url',$this->link_url,true);

		$criteria->compare('url_hash',$this->url_hash,true);

		$criteria->compare('url_host',$this->url_host,true);

		$criteria->compare('site_title',$this->site_title,true);

		$criteria->compare('news_tag',$this->news_tag,true);

		$criteria->compare('news_desc',$this->news_desc,true);

		$criteria->compare('user_id',$this->user_id);

		$criteria->compare('user_name',$this->user_name,true);

		$criteria->compare('digg_num',$this->digg_num);

		$criteria->compare('trash_num',$this->trash_num);

		$criteria->compare('comment_num',$this->comment_num);

		$criteria->compare('post_time',$this->post_time,true);

		$criteria->compare('update_time',$this->update_time,true);

		$criteria->compare('news_score',$this->news_score);

		$criteria->compare('news_thumb',$this->news_thumb,true);

		return new CActiveDataProvider(get_class($this), array(
			'criteria'=>$criteria,
		));
	}
	
	/**
	 * @return array a list of links that point to the post list filtered by every tag of this post
	 */
	public function getTagLinks()
	{
		$links=array();
		foreach(Tags::string2array($this->news_tag) as $key => $tag){
			if($tag){
				$links[$key]['tag_name']=CHtml::link(CHtml::encode($tag), array('/tag/index', 'tag'=>$tag),array('class'=>'tag'));
				$temp_tags_ar = Tags::model()->find('tag_name=:tag_name',array(':tag_name'=>$tag));
				$use_num = Tags::jsonToArray($temp_tags_ar->news_ids);
				$links[$key]['use_num'] = $use_num['use_num'];
			}
		}
		return $links;
	}
	public static function tagToLinks($tag,$database = false){
		$links=array();
		foreach(Tags::string2array($tag) as $key => $tag){
			if($tag){
				$links[$key]['tag_name']=CHtml::link(CHtml::encode($tag), array('/tag/index', 'tag'=>$tag));
				if($database){
					$temp_tags_ar = Tags::model()->find('tag_name=:tag_name',array(':tag_name'=>$tag));
					$use_num = Tags::jsonToArray($temp_tags_ar->news_ids);
					$links[$key]['use_num'] = $use_num['use_num'];
				}
			}
		}
		return $links;
	}
	
	public function normalizeTags($attribute,$params)
	{
		$this->news_tag=Tags::array2string(array_unique(Tags::string2array($this->news_tag)));
	}

	public function createNews($model){
		
		$transaction=$model->dbConnection->beginTransaction();
		try{
			$Links = new Links;
			$Links->user_id = Yii::app()->user->id;
			$Links->link_url = $model->link_url;
			$Links->site_name = $model->site_title;
			$Links->site_keyword = $this->news_tag;//$model->site_keyword;
			$Links->site_desc = $model->news_desc;
			
			//$link->site_type = 'link';
			$Links->post_time = time();
			$Links->save();
			$model->link_id = $Links->primaryKey;
			
			$model->save();
			//nc_user表(update)
			if(!User::updateByNews($this->news_tag)){
				$model->addError('user_id','user update error');
				//$transaction->rollBack();
				return false;
			}
			
			//nc_actions(insert)
			if(!Actions::addActions($model->primaryKey,'issue')){
				$model->addError('news_id','actions insert error');
				//$transaction->rollBack();
				return false;
			}
			//更新tag
			$new_tag_id = Tags::model()->updateTagUseNum($this->_oldTags, $this->news_tag,$this->news_id);
			$transaction->commit();
			
		}catch(Exception $e){
			$transaction->rollBack();
			return false;
		}
		return true;
	}

	public function beforeSave(){
		if(parent::beforeSave()){
			if($this->isNewRecord){
				$this->post_time = $this->update_time = time();
				$this->user_id = Yii::app()->user->id;
				$this->user_name = Yii::app()->user->name;
				$this->url_hash = md5($this->link_url);
				$this->url_host = self::parseUrl($this->link_url,'host');
				$this->news_score = 1;
			}else{
				$this->update_time = time();
			}
			return true;
		}
		return false;
	}
	
	public function afterSave(){
		parent::afterSave();
		//nc_news_tags表(insert)
		
		//NewsTags::addNewsTags($new_tag_id,$this->news_id);
		
	}
	/**
	 * This is invoked when a record is populated with data from a find() call.
	 */
	protected function afterFind()
	{
		parent::afterFind();
		$this->_oldTags=$this->news_tag;
	}
	public function parseUrl($url,$type){
		$newsUrl = NParseUrl::getUrlinfo($url);
		$this->_newsUrl= parse_url($newsUrl);
		return $this->_newsUrl[$type];
	}

	public static function validateUrlUnique($url){
		return self::model()->loadModelByLink($url);
	}
	private function loadModelByLink($url){
		return $this->find('url_hash=:url_hash',array(':url_hash'=>md5($url)));
	}
	public static function dataProvider(&$dataProvider,$colum,$attachColum=''){
		$attachColum = $attachColum ? $attachColum : $colum;
		$data = $dataProvider->getData();
		$count = count($data);
		switch($count){
			case '0':
				return $dataProvider;
			break;
			case '1':
				$newARtmp = News::model()->find("t.$colum = ".$data[0]->$colum);
				$data[0]->setAttribute($attachColum,$newARtmp);
				return $dataProvider;
				break;
			default:
				foreach($data as $key => $oldHandle){
					$tmpIds[] = $oldHandle->$colum;
					//$data[$oldHandle->$colum] = $oldHandle;
				}
				$tmpID = implode(',',$tmpIds);
				$newARtmp = News::model()->findAll("t.$colum in ($tmpID)");
				//改变key为$colum
				foreach($newARtmp as $key =>$v){
					$keyArray[$v->$colum] = $v;
				}
				//与dataProvider组合
				foreach($data as $key => $newHandle){
					$newHandle->setAttribute($attachColum,$keyArray[$newHandle->$colum]);
				}
				return ($dataProvider);
		}
	}
}